package com.zhupf.binaryTree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhupf
 * @date 2023年12月01日 10:19
 * @Description
 * 199. 二叉树的右视图
 */
public class RightSideView {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,new TreeNode(2,null,new TreeNode(5)),new TreeNode(3,null,new TreeNode(4)));
        List<Integer> list = rightSideView(root);
        System.out.println(list);
    }

    public static List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Deque<TreeNode> stk = new LinkedList<>();

        stk.offer(root);
        while (!stk.isEmpty()){
            int size = stk.size();
            while (size > 0 ){
                TreeNode node = stk.poll();
                if(node.left != null){
                    stk.offer(node.left);
                }
                if(node.right != null){
                    stk.offer(node.right);
                }
                if(size == 1){
                    res.add(node.val);
                }
                size--;
            }
        }
        return res;
    }

    public static List<Integer> rightSideView2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Deque<TreeNode> stk = new LinkedList<>();

        stk.offer(root);
        while (!stk.isEmpty()){
            int size = stk.size()-1;
            TreeNode node = stk.poll();
            while (size > 0 ){
                if(node.right != null){
                    stk.offer(node.left);
                }
                if(node.left != null){
                    stk.offer(node.right);
                }
                size--;
            }
        }
        return res;
    }
}
